package com.hangsu.train.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;


@Component
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ObjectFactory<NioWebSocketHandler> objectFactory;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        pipeline.addLast("decoder",new StringDecoder(Charset.forName("UTF-8")));
        pipeline.addLast("encoder",new StringEncoder(Charset.forName("UTF-8")));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(objectFactory.getObject());
    }
}
